﻿using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Tool.Models;
using Tool.Utils;
using Volo.Abp.DependencyInjection;

namespace Tool.Services
{
    public class TerminalService : IScopedDependency
    {
        private readonly IHttpClientFactory httpClientFactory;

        public TerminalService(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory;
        }

        public async Task<List<VoucherTerminalDto>> GetTerminalInfo(string sql, string clientName, HttpResponseHeaders? httpResponseHeader, string groupName)
        {
            var terminals = new List<VoucherTerminalDto>();
            var sqlContent = string.Empty;
            if (clientName == "sh")
            {
                sqlContent = sql;
            }
            else
            {
                sqlContent = Convert.ToBase64String(Encoding.UTF8.GetBytes(sql));
            }

            var query = "/query/";
            using (var httpClient = httpClientFactory.CreateClient(clientName))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Post, query);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}sqlquery/");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 获取响应头中的 Set-Cookie 字段
                if (httpResponseHeader == null)
                {
                    return terminals;
                }
                if (httpResponseHeader.TryGetValues("Set-Cookie", out var cookieValues))
                {
                    foreach (var cookie in cookieValues)
                    {
                        Console.WriteLine("Received Set-Cookie: " + cookie);
                        authRequest.Headers.Add("Cookie", cookie);
                    }
                }

                // 3. 获取 csrftoken（从 Cookie 中）
                // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                if (csrfCookie != null)
                {
                    var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                    if (csrfValue != null)
                    {
                        var token = csrfValue.Substring("csrftoken=".Length);
                        authRequest.Headers.Add("X-CSRFToken", token);
                    }
                }


                // 构建 Form 数据
                var content = FormHelper.GetSyncReimFormData(sqlContent, clientName, groupName);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                authRequest.Content = content;
                // 显式设置 Content-Type


                var postResponse = await httpClient.SendAsync(authRequest);
                if (postResponse.IsSuccessStatusCode)
                {
                    var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                    var jsonStr = Encoding.UTF8.GetString(responseBody);
                    Console.WriteLine(jsonStr);
                    //jsonStr转换成json对象
                    using (var doc = JsonDocument.Parse(jsonStr))
                    {
                        var root = doc.RootElement;

                        var rows = root.GetProperty("data").GetProperty("rows");
                        foreach (JsonElement item in rows.EnumerateArray())
                        {
                            terminals.Add(new VoucherTerminalDto
                            {
                                Id = item[0].ToString(),
                                TerminalSn = item[1].GetString(),
                                MachineCode = item[2].GetString(),
                                CheckCode = item[3].GetString(),
                                ExpirationTime = item[4].GetString(),
                                UserCode = item[5].GetString(),
                                CreateTime = item[6].GetString(),
                                UpdateTime = item[7].GetString(),
                                IsDeleted = item[8].GetInt16(),
                            });
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                    Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                }
            }

            return terminals;
        }
    }
}
